package org.grapes.wine.api.server.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.grapes.wine.api.method.EWineMethod;
import org.grapes.wine.api.server.method.MethodCommand;
import org.grapes.wine.api.server.method.factory.MethodCommandFactory;
import org.grapes.wine.api.server.method.impl.MethodList;
import org.w3c.dom.Document;

/**
 * Servlet implementation class UserXMLServlet
 */
public class UserXMLServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private TransformerFactory transformerFactory;
	
	public void init() {
		transformerFactory = TransformerFactory.newInstance();	
	}
	
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		MethodCommand getUserMethod = MethodCommandFactory.newInstance(EWineMethod.GET_USER);
		Document doc = getUserMethod.execute(request);
		renderDocument(doc, request, response);
	}
	
	protected void renderDocument(Document doc, HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/xml");
		try {
			Transformer identity = transformerFactory.newTransformer();

			Result result = new StreamResult(response.getOutputStream());
			identity.transform(new DOMSource(doc), result);
		} catch (TransformerException e) {
			throw new ServletException(
					"Unable to preform identity transformation", e);
		}
	}
}
